import { fileSizeApi, downloadFileApi, downloadChunkApi } from '@/api/file'
import { getChunkArgs, CHUNK_SIZE } from '@/utils/fileUtil'
import { sleep } from '@/utils/func'

export const getFileSrc = async (filePath: string, fileName?: string) => {
  let percent = -1,
  size = 0,
  pause = false

  const fileSize = await fileSizeApi(filePath)
  const chunks: Blob[] = []
  if(fileSize > CHUNK_SIZE) {
    const chunkArgs = getChunkArgs(fileSize)
    percent = 0
    for(const i in chunkArgs) {
      while(pause) await sleep(100)

      const { offset, length } = chunkArgs[i]
      const chunk = await downloadChunkApi(filePath, offset, length)
      chunks.push(chunk)
      size += length
      percent = parseFloat(((size / fileSize) * 100).toFixed(2))
    }
  } else {
    const chunk = await downloadFileApi(filePath)
    chunks.push(chunk)
    size = fileSize
    percent = 99
  }

  percent = 100
  // return new File(chunks, fileName)
  const fileSuffix = filePath.split('.').pop()
  fileName = fileName ?? `${Date().valueOf().toString()}.${fileSuffix}`
  const result = URL.createObjectURL(new File(chunks, fileName))
  console.log('result:', result)
  return result
}
